package cn.ybk.system.service.impl;

import cn.ybk.system.domain.Permission;
import cn.ybk.system.domain.Role;
import cn.ybk.system.mapper.MenuMapper;
import cn.ybk.system.mapper.PermissionMapper;
import cn.ybk.system.mapper.RoleMapper;
import cn.ybk.system.service.IRoleService;
import cn.ybk.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    @Transactional
    public void add(Role role) {
        super.add(role);
        // 添加role-menu中间表
        menuMapper.addToMenus(role.getId(),role.getMenus());
        // 添加role-permissions中间表
        permissionMapper.addToPermissions(role.getId(),role.getPermissions());
    }

    @Override
    @Transactional
    public void update(Role role) {
        super.update(role);
        // 先删除里面的数据
        menuMapper.deleteByRole(role.getId());
        // 在添加里面的数据
        menuMapper.addToMenus(role.getId(),role.getMenus());
        // 先删除里面的数据
        permissionMapper.deleteByRole(role.getId());
        // 在添加里面的数据
        permissionMapper.addToPermissions(role.getId(),role.getPermissions());
    }

    @Override
    public void delete(Long id) {
        super.delete(id);
        menuMapper.deleteByRole(id);
        permissionMapper.deleteByRole(id);
    }
}
